<?php
namespace app\admin\controller;
use \app\admin\controller\BaseController;
use app\admin\model\Shop;
use think\Db;

class Spike extends BaseController
{
	/**
	 * 渲染秒杀界面
	 * @return [type] [description]
	 */
	public function index()
	{
		$this->isLogin();
		return view('', compact(''));
	}
	/**
	 * 切换秒杀商品
	 * @return [type] [description]
	 */
	public function checkSpike(Shop $shop)
	{
		$this->isLogin();
		Db::startTrans(); //开启事务
		try {
			$list = $shop->where(['spike' => 1, 'shop_delete' => 0, 'audit' => 1, 'is_use' => 0])->field('id')->select()->toArray();
			if($list) {
				foreach ($list as $key => $value) {
					$spike_list = $this->setSpike($value['id'], 1);
					if(!$spike_list) {
						$this->error('秒杀商品更换失败');
					}
				}
			}
			$shop_list = $shop->where(['shop_delete' => 0, 'audit' => 1, 'is_use' => 0])->order('rand()')->limit(8)->field('id')->select()->toArray();
			foreach ($shop_list as $key => $value) {
				$spike_list = $this->setSpike($value['id'], 2);
				if(!$spike_list) {
						$this->error('秒杀商品更换失败');
				}
			}
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
		}
		
		$this->success('秒杀商品更换成功');
	}
	/**
	 * 设置秒杀
	 * @param [type] $shop_id [description]
	 * @param [type] $type    [description]
	 */
	public function setSpike($shop_id, $type) 
	{
		$this->isLogin();
		$shop = new Shop();
		if($type == '1') {
			$spike = $shop->where(['id' => $shop_id])->update(['spike' => 0]);
			if(!$spike) {
				return false;
			}

		} else if($type == '2') {
			$spike = $shop->where(['id' => $shop_id])->update(['spike' => 1]);
			if(!$spike) {
				return false;
			}
		}
		return true;
	}
    /**
     * 开启秒杀管理
     */
    public function spikeStart()
    {
    	$this->isLogin();
        return view('secKill/secKill');
    }

}
